/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package listElement;

import td1exo.List;

/**
 *
 * @author Administrateur
 */
public class CircularLinkedList<E> extends LinkedList<E> implements List<E> {

    public CircularLinkedList() {
        super();
    }

    /*========================================================================*/
    @Override
    public E getNext(Object o) {

        if (first == null || o == null) {
            return null;
        }

        if(last.equals(o)){
            return first.getElement();
        }

        ListElement<E> find = first;
        while (find != null && !find.equals(o)) {
            find = find.getNext();
        }//end while
        return find != null && find.getNext() != null ? find.getNext().getElement() : null;
    }

    /*========================================================================*/
    @Override
    public E getNext(int index) {

        if (first == null) {
            return null;
        }

        if(last.getPosition() == index){
            return first.getElement();
        }

        ListElement<E> find = first;
        while (find.getPosition() != index) {
            find = find.getNext();
        }//end while

        return find != null && find.getNext() != null ? find.getNext().getElement() : null;
    }

    /*========================================================================*/
    @Override
    public List<E> subList(int fromIndex, int toIndex) {

        List<E> sublist = new CircularLinkedList();

        if (first == null || last.getPosition() < fromIndex || fromIndex > toIndex) {
            return sublist;
        }

        ListElement<E> find = first;
        while (find != null && find.getPosition() != toIndex) {
            if (find.getPosition() >= fromIndex) {
                sublist.add(find.getElement());
            }
            find = find.getNext();
        }

        return sublist;
    }

    /*========================================================================*/
    @Override
    public String toString() {

        if (first == null) {
            return "Empty LinkedList !!!";
        }

        StringBuilder stringBuilder = new StringBuilder();
        ListElement<E> find = first;
        stringBuilder.append("CircularLinked List [\n");
        while (find != null) {
            stringBuilder.append("\t Element " + find.getPosition() + " : " + find.getElement().toString() + "\n");
            find = find.getNext();
        }
        stringBuilder.append("]");

        return stringBuilder.toString();
    }
}
